<template>

</template>

<script lang="ts" setup>


import {useRouter} from "vue-router";

const router = useRouter();
import {isEmpty} from "../../../../utils/utils";


const scope: string = 'snsapi_userinfo' // 授权方式
const urls:string = 'http://wxpro.xlmediawatch.com' ;



/**
 * 获取微信授权appid
 */
const getAuthorize = async (url:string) => {
  try {
    await getAjax('get', `http://59.110.22.117/wechat/sign?url=${url}`, '', url)
  } catch (e) {
    console.log(e);
  }
}


/**
 * 获取url上query
 */
const getQuery = () => {
  let query: any = {}
  const url = window.location.href
  if (url.indexOf('?') !== -1) {
    let queryArr: Array<string> = []
    const urlQuery: string = url.split('?')[1]
    if (urlQuery.indexOf('&') !== -1) {
      queryArr = urlQuery.split('&')
    } else {
      queryArr = [urlQuery]
    }
    for (let i: number = 0; i < queryArr.length; i++) {
      if (queryArr[i].indexOf('=') !== -1) {
        const key: any = queryArr[i].split('=')[0]
        const value: any = queryArr[i].split('=')[1]
        query[key] = value
      }
    }
  }
  return query
}


const urlQuery:any = getQuery()


/**
 * 封装ajax
 * @param _methods 调用请求  post  get 。。。
 * @param url  请求地址
 * @param _data  请求参数
 * @param desc  描述
 */
const getAjax = (_methods: string, url: string, _data: any) => {
  return new Promise((resolve, reject) => {
    let xhr: XMLHttpRequest;
    if (XMLHttpRequest) {
      xhr = new XMLHttpRequest()
    } else {
      xhr = new ActiveXObject()
    }
    let data = _data || null;
    let methods = _methods || 'get';
    xhr.open(methods, url, true)
    // 设置请求头
    xhr.send(data)
    xhr.onreadystatechange = () => {
      if (xhr.readyState === 4) {
        const result:any = JSON.parse(xhr.responseText)
        // 前端使用appid和回调域名来获取微信登陆二维码
        const appid: string = result.appId // appid
        // 本地调试
        const local:boolean = true
        if(isEmpty(urlQuery.code) && !local){
          // // 前端使用appid和回调域名来获取微信登陆二维码
          const scope: string = 'snsapi_userinfo' // 授权方式 snsapi_base 静默授权    snsapi_userinfo  需要验证
          window.location.replace(`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(urls)}&response_type=code&scope=${scope}&state=STATE#wechat_redirect`)
        }else{
          router.push(
              {
                path: "/salesPromotion/login",
                query:urlQuery
              })
        }
        // window.location.replace(`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${encodeURIComponent(urls)}&response_type=code&scope=${scope}&state=123#wechat_redirect`)
      }
    }
  })
}


/**
 * 调用获取授权appid
 */
getAuthorize(urls)


// router.push({path: "/salesPromotion/login"});
</script>

<style scoped>

</style>